package com.netty.rpc.handler;

import com.netty.rpc.listener.ServerFutureListener;
import com.netty.rpc.req.CalcRequest;

import com.netty.rpc.resp.Response;
import com.netty.rpc.thread.WorkerTask;
import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Future;


import java.util.Map;

public class NettyServerHandler extends  SimpleChannelInboundHandler<CalcRequest>{

    private Map<String, Object> servicesMap;

    public NettyServerHandler(Map<String, Object> servicesMap){
        this.servicesMap = servicesMap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CalcRequest request){
        try {
            /*ByteBuf byteBuf = ByteBufAllocator.DEFAULT.directBuffer();
            byteBuf.writeBytes("netty byte 。。。。".getBytes());
            String serviceName = request.getServiceName();
            String methodName = request.getMethodName();
            Class[] paramsTypes = request.getParamsTypes();
            Object[] params = request.getParams();
            Object service = servicesMap.get(serviceName);
            Method method = service.getClass().getMethod(methodName, paramsTypes);
            Object result = method.invoke(service, params);
            CalcResponse response = new CalcResponse();
            response.setResult(result);
            channelHandlerContext.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);*/
            Future<Response> future = ctx.executor().submit(new WorkerTask(ctx, request, servicesMap));
            future.addListener(new ServerFutureListener(ctx));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel active ....");
        super.channelActive(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel handler added ....");
        super.handlerAdded(ctx);
    }
}
